package com.db.history.messages;

import com.db.history.files.FileOperations;
import com.db.services.Settings;

import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Class for List with messages
 */
public class MessageHistory {
    private final ReentrantReadWriteLock fLock = new ReentrantReadWriteLock();
    private final Lock fReadLock = fLock.readLock();
    private final Lock fWriteLock = fLock.writeLock();
    private FileOperations fo;

    /**
     * Save chat history
     */
    public MessageHistory() {
        fo = new FileOperations();
    }



    /**
     * Get all messages since server started
     * Has readLock
     * @return string contains all messages
     */
    public String getMessages() {
        fReadLock.lock();
        try {
            StringBuffer sb = fo.ReadFile();
            return (sb != null ? sb.toString() : "");
        } finally {
            fReadLock.unlock();
        }
    }

    /**
     * Add message to the list
     * If messages in list more then MAX_MESSAGE_NUMBER or heap is used over then 50% then write messages to file
     * Has writeLock
     * @param message
     */
    public void addMessage(Message message) {
        fWriteLock.lock();
        try {
            fo.SaveToFile(message.toString());
        } finally {
            fWriteLock.unlock();
        }
    }
}
